<template>
    <section>
        <!--获取权限按钮-->
        <toolbar :buttonList="buttonList" @callFunction="callFunction"></toolbar>
        <el-table 
            :data="users" 
            style="width: 100%;" 
            @select="dialogCheck"
            @row-click="selectCurrentRow" 
            ref="table"
            >

            <el-table-column type="selection" width="50" /> 
            <el-table-column type="index" width="80" /> 
            <el-table-column prop="realName" label="昵称" width="150" sortable />
            <el-table-column prop="loginName" label="登录名" width="100" sortable />
            <el-table-column prop="roleNames" label="角色" width="180" sortable>
                <template v-slot="scope">
                <el-tag v-for="item in scope.row.roleNames" :key="item.Id">{{
                    item
                }}</el-tag>
                </template>
            </el-table-column>
            
            <el-table-column prop="departmentName" label="所属部门" width="180" sortable />
            <el-table-column prop="sex" width="80"
                :formatter="function(row){ return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知'}"
                label="性别"
                sortable />
            <el-table-column
                prop="birth"
                label="生日"
                width="200"
                sortable
            />
            <el-table-column prop="status" label="状态" sortable>
                <template v-slot="scope">
                <el-tag
                    :type="scope.row.status == 0 ? 'success' : 'danger'"
                    disable-transitions
                    >{{ scope.row.status == 0 ? "正常" : "禁用" }}
                </el-tag>
                </template>
            </el-table-column>

            <el-table-column fixed="right" label="操作" width="120">
                <template #default="scope">
                    <el-button
                    link
                    type="primary"
                    size="small"
                    @click.prevent="removePwd(scope.$index)"
                    >
                    重置密码
                    </el-button>
                </template>
            </el-table-column>

        </el-table>

        <!--页码-->
        <el-col :span="24" class="toolbar">
            <el-pagination
                layout="prev, pager, next"
                :page-size="50"
                :total="total"
                style="float: right"
            >
            </el-pagination>
        </el-col>

        <!--新增 （弹窗）-->
        <el-dialog v-model="dialogAddUser" title="新增">
            <el-form :model="AddForm" label-width="80px">
            <el-form-item label="昵称">
                <el-input v-model="AddForm.realName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="登录名" >
                <el-input v-model="AddForm.loginName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="密码" >
                <el-input v-model="AddForm.loginPWD" autocomplete="off" show-password />
            </el-form-item>
            <el-form-item label="角色">
                <el-select
                    v-model="AddForm.riDs"
                    multiple
                    filterable
                    allow-create
                    default-first-option
                    :reserve-keyword="false"
                    placeholder="请选择用户角色"
                >
                    <el-option
                        v-for="item in roles[0]"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>

            <el-form-item
                label="所属部门"
                v-if="options && options.length > 0"
                prop="dids"
                >
                <el-cascader
                    placeholder="请选择，支持搜索功能"
                    style="width: 100%"
                    v-model="AddForm.dids"
                    :options="options"
                    filterable
                    :key="isResouceShow"
                    :props="{ checkStrictly: true, expandTrigger: 'hover' }"
                ></el-cascader>
            </el-form-item>

            <el-form-item label="性别">
                <el-radio-group v-model="AddForm.sex">
                    <el-radio class="radio" :label="1">男</el-radio>
                    <el-radio class="radio" :label="0">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="年龄">
                <el-input-number v-model="AddForm.age" :min="0" :max="200"></el-input-number>
            </el-form-item>
            <el-form-item label="生日">
                <el-date-picker type="date" placeholder="选择日期" v-model="AddForm.birth"></el-date-picker>
            </el-form-item>
            <el-form-item label="地址">
                <el-input type="textarea" v-model="AddForm.addr"></el-input>
            </el-form-item>


            </el-form>
            <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogAddUser = false">取消</el-button>
                <el-button type="primary" @click="addSubmit">
                确定
                </el-button>
            </span>
            </template>
        </el-dialog>

        <!--编辑 （弹窗）-->
        <el-dialog v-model="dialogEditUser" title="编辑">
            <el-form :model="EditForm" label-width="80px">
            <el-form-item label="昵称">
                <el-input v-model="EditForm.realName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="登录名" >
                <el-input v-model="EditForm.loginName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="密码" >
                <el-input v-model="EditForm.loginPWD" autocomplete="off" show-password />
            </el-form-item>

            <el-form-item label="角色">
                <el-select
                    v-model="EditForm.riDs"
                    multiple
                    filterable
                    allow-create
                    default-first-option
                    :reserve-keyword="false"
                    placeholder="请选择用户角色"
                >
                    <el-option
                        v-for="item in roles[0]"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>

            <el-form-item
                label="所属部门"
                v-if="options && options.length > 0"
                prop="dids"
                >
                <el-cascader
                    placeholder="请选择，支持搜索功能"
                    style="width: 100%"
                    v-model="EditForm.dids"
                    :options="options"
                    filterable
                    :key="isResouceShow"
                    :props="{ checkStrictly: true, expandTrigger: 'hover' }"
                ></el-cascader>
            </el-form-item>

            <el-form-item label="性别">
                <el-radio-group v-model="EditForm.sex">
                    <el-radio class="radio" :label="1">男</el-radio>
                    <el-radio class="radio" :label="0">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="年龄">
                <el-input-number v-model="EditForm.age" :min="0" :max="200"></el-input-number>
            </el-form-item>
            <el-form-item label="生日">
                <el-date-picker type="date" placeholder="选择日期" v-model="EditForm.birth"></el-date-picker>
            </el-form-item>
            <el-form-item label="地址">
                <el-input type="textarea" v-model="EditForm.address"></el-input>
            </el-form-item>


            </el-form>
            <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogEditUser = false">取消</el-button>
                <el-button type="primary" @click="editSubmit">
                确定
                </el-button>
            </span>
            </template>
        </el-dialog>

    </section>
</template>

<script>
import {getUserListPage,getDepartmentTree,editUserInfo,getRoleList,delUserInfo,postUserInfo} from '@/api/api';
import Toolbar from '../../components/Toolbar.vue'
export default{
    components:{
        Toolbar
    },
    data(){
        return{
            //关键字搜索
            searchVal:'',
            page:1,
            total:1,
            //列表是否加载中
            listLoading:false,
            users:[],
            roles:[],
            dialogAddUser:false,
            AddForm:{
                name: "",
                loginName: "",
                realName: "",
                loginPWD: "",
                riDs:[],
                sex: 1,
                age: 0,
                birth: "",
                dids: [],
                DepartmentId: 0,
                addr: "",
            },
            dialogEditUser:false,
            EditForm:{},
            options:[],
            isResouceShow:0,
            currentRow:null,
            buttonList:[]
        }
    },
    methods:{
        dialogCheck(selection, row) {
            this.currentRow = null;
            this.$refs.table.clearSelection();
            if (selection.length === 0) {
                return;
            }
            if (row) {
                this.selectCurrentRow(row);
            }
        },
        selectCurrentRow(val) {
            if (val) {
                this.currentRow = val;
                this.$refs.table.clearSelection();
                this.$refs.table.toggleRowSelection(val, true);
            }
        },
        callFunction(item) {
            this.searchVal = item.search;
            //const methodList = this.$options.methods;
            //methodList[item.func]();

            this[item.func](this, item);
        },
        /**获取用户列表 */
        getUsers(){
            let para = {
                page: this.page,
                key: this.searchVal,
            };
            this.listLoading = true;

            getUserListPage(para).then((res) => {
                console.log(res)
                this.users = res.response.data;
                this.listLoading = false;
            });
        },
        /**删除 */
        handleDel(){
            let _this = this;

            let row = _this.currentRow;
        
            console.log('currentRow',row)
            if (!row) {
                //ElMessage({
                _this.$message({
                    message: "请选择要删除的一行数据！",
                    type: "error",
                });
                return;
            }

            let param = {
                uid:row.id
            }
            delUserInfo(param).then(res=>{
                if(res.success){
                    _this.$message({
                        message: "删除成功",
                        type: "success",
                    });
                    _this.getUsers();
                }else{
                    _this.$message({
                        message: res.msg?res.msg:'删除失败！',
                        type: "error",
                    });
                }
            })
        },
        /**新增 */
        handleAdd(){
            this.dialogAddUser = true;

            this.options = [];
            this.roles = [];
            let param = {
            }
            getRoleList(param).then((res)=>{
                this.roles.push(res.response.data);
            })
            
            let para = {
                pid:0
            }
            getDepartmentTree(para).then((res)=>{
                this.options.push(res.data.response);
            })

        },
        /**编辑 */
        handleEdit(){
            let row = this.currentRow;
            if (!row) {
                //ElMessage({
                this.$message({
                message: "请选择要编辑的一行数据！",
                type: "error",
                });
                return;
            }

            this.dialogEditUser = true;
            this.options = [];
            this.roles = [];
            let param = {
            }
            getRoleList(param).then((res)=>{
                this.roles.push(res.response.data);
            })
            
            let para = {
                pid:0
            }
            getDepartmentTree(para).then((res)=>{
                this.options.push(res.data.response);
            })

            this.EditForm = row;
        },
        /**新增提交 */
        addSubmit: function(){
            let _this = this;

            //console.log('AddForm',this.AddForm)
            let param = this.AddForm;
            param.name = param.loginName;
            postUserInfo(param).then(res=>{
                if(res.success){
                    _this.$message({
                        message: res.msg?res.msg:"添加成功",
                        type: "error",
                    });
                    _this.dialogAddUser = false
                }else{
                    _this.$message({
                        message: res.msg?res.msg:"添加失败",
                        type: "error",
                    });
                }
            })
            
        },
        /**编辑提交 */
        editSubmit: function(){
            var _this = this;
            _this.EditForm.departmentId = this.EditForm.dids[_this.EditForm.dids.length-1]
            editUserInfo(_this.EditForm).then((res)=>{
                if(res.success){
                    _this.$notify({
                        type: "success",
                        message: `修改成功！`,
                        duration: 6000
                    });
                    _this.dialogEditUser = false;
                    _this.getUsers();
                }
            });
        },
        /**重置密码 */
        removePwd(index){
            console.log(this.users[index]);
        },
        getbuttonList(path1,router){
            router.forEach(element => {
                if (path1&&element.path) {
                    if (element.path && element.path.toLowerCase() === path1.toLowerCase()) {
                        this.buttonList = element.children;
                        return;
                    } else if (element.children) {
                        this.getbuttonList(path1,element.children);
                    }
                }
            });
        }
    },
    mounted(){
        this.getUsers();

        let routers = window.localStorage.router ? JSON.parse(window.localStorage.router) : [];

        this.getbuttonList(this.$route.path,routers);

        //console.log('buttonList',this.buttonList);
    }
}
</script>


<style scoped>
.custom-tbl /deep/ .has-gutter .el-checkbox {
  display: none;
}
</style>